// 收银台交互逻辑
(function() {
    // 商品数据模型（模拟数据）
    const products = [
        { id: '001', name: '可口可乐 500ml', price: 3.50, barcode: '6921168509256' },
        { id: '002', name: '农夫山泉 550ml', price: 2.00, barcode: '6921168509263' },
        { id: '003', name: '康师傅红烧牛肉面', price: 4.50, barcode: '6921168509270' },
        { id: '004', name: '乐事薯片 原味 40g', price: 5.00, barcode: '6921168509287' },
        { id: '005', name: '德芙巧克力 牛奶味 86g', price: 12.50, barcode: '6921168509294' }
    ];

    // 购物车数据
    let cart = [];

    // DOM元素缓存
    const barcodeInput = document.getElementById('barcode-input');
    const manualInputBtn = document.getElementById('manual-input-btn');
    const productList = document.getElementById('product-list');
    const totalAmount = document.getElementById('total-amount');
    const paymentBtn = document.getElementById('payment-btn');
    const clearCartBtn = document.getElementById('clear-cart-btn');
    const scanModeBtn = document.getElementById('scan-mode-btn');
    const manualModeBtn = document.getElementById('manual-mode-btn');

    // 初始化页面
    function init() {
        // 绑定事件监听器
        if (barcodeInput) {
            barcodeInput.addEventListener('keydown', handleBarcodeInput);
            barcodeInput.focus();
        }

        if (manualInputBtn) {
            manualInputBtn.addEventListener('click', showManualInputModal);
        }

        if (paymentBtn) {
            paymentBtn.addEventListener('click', processPayment);
        }

        if (clearCartBtn) {
            clearCartBtn.addEventListener('click', clearCart);
        }

        if (scanModeBtn) {
            scanModeBtn.addEventListener('click', switchToScanMode);
        }

        if (manualModeBtn) {
            manualModeBtn.addEventListener('click', switchToManualMode);
        }

        // 初始化设置
        loadSettings();
        updateCartDisplay();
    }

    // 处理扫码输入
    function handleBarcodeInput(event) {
        if (event.key === 'Enter' && barcodeInput.value.trim() !== '') {
            const barcode = barcodeInput.value.trim();
            addProductByBarcode(barcode);
            barcodeInput.value = '';
            barcodeInput.focus();
        }
    }

    // 通过条形码添加商品
    function addProductByBarcode(barcode) {
        const product = products.find(p => p.barcode === barcode);
        if (product) {
            addToCart(product);
            showSuccessMessage(`已添加: ${product.name}`);
        } else {
            showErrorMessage(`未找到商品: ${barcode}`);
        }
    }

    // 添加商品到购物车
    function addToCart(product) {
        const existingItem = cart.find(item => item.id === product.id);
        if (existingItem) {
            existingItem.quantity += 1;
        } else {
            cart.push({
                ...product,
                quantity: 1
            });
        }
        updateCartDisplay();
    }

    // 更新购物车显示
    function updateCartDisplay() {
        if (!productList || !totalAmount) return;

        // 清空购物车列表
        productList.innerHTML = '';

        // 计算总金额
        let total = 0;

        // 添加商品到列表
        cart.forEach((item, index) => {
            const itemTotal = item.price * item.quantity;
            total += itemTotal;

            const row = document.createElement('div');
            row.className = 'cart-item d-flex justify-content-between align-items-center p-2 border-bottom';
            row.innerHTML = `
                <div class="item-info">
                    <div class="item-name">${item.name}</div>
                    <div class="item-price">¥${item.price.toFixed(2)}</div>
                </div>
                <div class="item-quantity">
                    <button class="btn btn-sm btn-secondary decrease-quantity" data-index="${index}">-</button>
                    <span class="mx-2">${item.quantity}</span>
                    <button class="btn btn-sm btn-secondary increase-quantity" data-index="${index}">+</button>
                </div>
                <div class="item-total">¥${itemTotal.toFixed(2)}</div>
                <button class="btn btn-sm btn-danger remove-item" data-index="${index}">
                    <i class="fa fa-trash"></i>
                </button>
            `;
            productList.appendChild(row);
        });

        // 更新总金额
        totalAmount.textContent = total.toFixed(2);

        // 绑定购物车项目事件
        bindCartItemEvents();

        // 更新支付按钮状态
        if (paymentBtn) {
            paymentBtn.disabled = cart.length === 0;
        }
    }

    // 绑定购物车项目事件
    function bindCartItemEvents() {
        // 减少数量
        document.querySelectorAll('.decrease-quantity').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.getAttribute('data-index'));
                decreaseQuantity(index);
            });
        });

        // 增加数量
        document.querySelectorAll('.increase-quantity').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.getAttribute('data-index'));
                increaseQuantity(index);
            });
        });

        // 移除商品
        document.querySelectorAll('.remove-item').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.getAttribute('data-index'));
                removeItem(index);
            });
        });
    }

    // 减少商品数量
    function decreaseQuantity(index) {
        if (cart[index].quantity > 1) {
            cart[index].quantity -= 1;
        } else {
            cart.splice(index, 1);
        }
        updateCartDisplay();
    }

    // 增加商品数量
    function increaseQuantity(index) {
        cart[index].quantity += 1;
        updateCartDisplay();
    }

    // 移除商品
    function removeItem(index) {
        cart.splice(index, 1);
        updateCartDisplay();
    }

    // 清空购物车
    function clearCart() {
        if (cart.length > 0 && confirm('确定要清空购物车吗？')) {
            cart = [];
            updateCartDisplay();
            showSuccessMessage('购物车已清空');
        }
    }

    // 处理支付
    function processPayment() {
        if (cart.length === 0) {
            showErrorMessage('购物车为空，无法结算');
            return;
        }

        // 获取总金额
        const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);

        // 这里可以添加支付逻辑，现在简化处理
        showPaymentModal(total);
    }

    // 显示支付弹窗
    function showPaymentModal(total) {
        // 创建支付弹窗
        const modal = document.createElement('div');
        modal.className = 'modal fade show';
        modal.style.display = 'block';
        modal.innerHTML = `
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">支付确认</h5>
                        <button type="button" class="close" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <p class="mb-3">总金额: <strong>¥${total.toFixed(2)}</strong></p>
                        <div class="form-group">
                            <label for="payment-amount">实付金额:</label>
                            <input type="number" id="payment-amount" class="form-control" min="${total}" step="0.01" value="${total}">
                        </div>
                        <div class="form-group">
                            <label for="payment-method">支付方式:</label>
                            <select id="payment-method" class="form-control">
                                <option value="cash">现金</option>
                                <option value="alipay">支付宝</option>
                                <option value="wechat">微信支付</option>
                                <option value="card">银行卡</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary cancel-payment">取消</button>
                        <button type="button" class="btn btn-primary confirm-payment">确认支付</button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        // 添加背景遮罩
        const backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show';
        document.body.appendChild(backdrop);

        // 绑定事件
        modal.querySelector('.close').addEventListener('click', closePaymentModal);
        modal.querySelector('.cancel-payment').addEventListener('click', closePaymentModal);
        modal.querySelector('.confirm-payment').addEventListener('click', () => {
            const paymentAmount = parseFloat(document.getElementById('payment-amount').value);
            const paymentMethod = document.getElementById('payment-method').value;
            completePayment(total, paymentAmount, paymentMethod);
            closePaymentModal();
        });

        function closePaymentModal() {
            modal.remove();
            backdrop.remove();
        }
    }

    // 完成支付
    function completePayment(total, paymentAmount, paymentMethod) {
        const change = paymentAmount - total;
        
        // 生成收据
        generateReceipt(total, paymentAmount, change, paymentMethod);
        
        // 清空购物车
        cart = [];
        updateCartDisplay();
        
        // 显示支付成功消息
        showSuccessMessage(`支付成功！找零: ¥${change.toFixed(2)}`);
    }

    // 生成收据
    function generateReceipt(total, paymentAmount, change, paymentMethod) {
        // 这里可以实现收据打印逻辑，现在简化处理
        const receiptContent = `
====== 超市购物清单 ======
${new Date().toLocaleString()}
-------------------------
${cart.map(item => `${item.name} x${item.quantity} ¥${(item.price * item.quantity).toFixed(2)}`).join('\n')}
-------------------------
总计: ¥${total.toFixed(2)}
实付: ¥${paymentAmount.toFixed(2)}
找零: ¥${change.toFixed(2)}
支付方式: ${getPaymentMethodText(paymentMethod)}
====== 感谢您的光临 ======`;
        
        console.log('收据内容:', receiptContent);
        
        // 这里可以添加打印逻辑，例如调用收据打印机API
        // 示例：printReceipt(receiptContent);
    }

    // 获取支付方式文本
    function getPaymentMethodText(method) {
        const methods = {
            cash: '现金',
            alipay: '支付宝',
            wechat: '微信支付',
            card: '银行卡'
        };
        return methods[method] || method;
    }

    // 显示手动输入商品弹窗
    function showManualInputModal() {
        // 创建手动输入弹窗
        const modal = document.createElement('div');
        modal.className = 'modal fade show';
        modal.style.display = 'block';
        modal.innerHTML = `
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">手动添加商品</h5>
                        <button type="button" class="close" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="manual-product-id">商品编号:</label>
                            <input type="text" id="manual-product-id" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="manual-product-quantity">数量:</label>
                            <input type="number" id="manual-product-quantity" class="form-control" min="1" value="1">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary cancel-manual-input">取消</button>
                        <button type="button" class="btn btn-primary confirm-manual-input">确认添加</button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        // 添加背景遮罩
        const backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show';
        document.body.appendChild(backdrop);

        // 绑定事件
        modal.querySelector('.close').addEventListener('click', closeManualInputModal);
        modal.querySelector('.cancel-manual-input').addEventListener('click', closeManualInputModal);
        modal.querySelector('.confirm-manual-input').addEventListener('click', () => {
            const productId = document.getElementById('manual-product-id').value.trim();
            const quantity = parseInt(document.getElementById('manual-product-quantity').value) || 1;
            
            if (productId) {
                addProductById(productId, quantity);
                closeManualInputModal();
            } else {
                showErrorMessage('请输入商品编号');
            }
        });

        function closeManualInputModal() {
            modal.remove();
            backdrop.remove();
        }
    }

    // 通过ID添加商品
    function addProductById(productId, quantity) {
        const product = products.find(p => p.id === productId);
        if (product) {
            for (let i = 0; i < quantity; i++) {
                addToCart(product);
            }
            showSuccessMessage(`已添加: ${product.name} x${quantity}`);
        } else {
            showErrorMessage(`未找到商品: ${productId}`);
        }
    }

    // 切换到扫码模式
    function switchToScanMode() {
        if (barcodeInput) {
            barcodeInput.style.display = 'block';
            barcodeInput.focus();
            showSuccessMessage('已切换到扫码模式');
        }
    }

    // 切换到手动模式
    function switchToManualMode() {
        if (barcodeInput) {
            barcodeInput.style.display = 'none';
            showManualInputModal();
        }
    }

    // 显示成功消息
    function showSuccessMessage(message) {
        showMessage(message, 'success');
    }

    // 显示错误消息
    function showErrorMessage(message) {
        showMessage(message, 'danger');
    }

    // 显示消息
    function showMessage(message, type) {
        const messageContainer = document.createElement('div');
        messageContainer.className = `alert alert-${type} fixed-top mx-auto mt-4 w-50`;
        messageContainer.style.zIndex = '9999';
        messageContainer.textContent = message;
        document.body.appendChild(messageContainer);

        // 3秒后自动关闭
        setTimeout(() => {
            messageContainer.classList.add('fade');
            setTimeout(() => {
                messageContainer.remove();
            }, 300);
        }, 3000);
    }

    // 加载设置
    function loadSettings() {
        // 从localStorage加载设置
        const settings = JSON.parse(localStorage.getItem('cashierSettings')) || {
            cashierName: '',
            printerName: '',
            currencyFormat: 'CNY',
            printCopies: 1,
            showLogo: true,
            showQrCode: true,
            showCurrencySymbol: true,
            autoRound: false
        };

        // 应用设置
        applySettings(settings);
    }

    // 应用设置
    function applySettings(settings) {
        // 这里可以根据设置调整收银台界面
        // 例如显示收银员名称、设置货币格式等
        console.log('应用设置:', settings);
    }

    // 保存设置
    function saveSettings(settings) {
        localStorage.setItem('cashierSettings', JSON.stringify(settings));
        applySettings(settings);
        showSuccessMessage('设置已保存');
    }

    // 暴露公共方法
    window.cashier = {
        init,
        addProductByBarcode,
        addProductById,
        clearCart,
        processPayment,
        loadSettings,
        saveSettings
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        init();
    });
})();